package com.wj.wjpicturebackend.manager.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.wj.wjpicture.infrastructure.config.RabbitMqConfig;
import com.wj.wjpicture.infrastructure.api.CosManager;
import com.wj.wjpicture.interfaces.dto.picture.PictureTaskMessage;
import com.wj.wjpicture.domain.picture.entity.Picture;
import com.wj.wjpicture.application.service.PictureApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Component
public class FormatConvertConsumer {

    @Resource
    private CosManager cosManager;

    @Resource
    private PictureApplicationService pictureApplicationService;

    /**
     * 处理图片格式转换任务（如转为webp）
     */
    @RabbitListener(queues = RabbitMqConfig.FORMAT_CONVERT_QUEUE)
    public void handleFormatConvertTask(PictureTaskMessage message, Channel channel, Message msg) throws IOException {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        InputStream objectContent = null;
        FileOutputStream outputStream = null;
        try {
            log.info("开始处理格式转换，pictureId: {}", message.getPictureId());

            // 1. 下载原图到本地临时文件
            String originalUrl = message.getOriginalUrl();
            String key = originalUrl.replace(cosManager.cosClientConfig.getHost() + "/", "");

            // 创建临时文件
            File tempFile = File.createTempFile("convert_", "." + message.getFileSuffix());

            // 正确的文件下载方式：使用输入流和输出流
            objectContent = cosManager.getObject(key).getObjectContent();
            outputStream = new FileOutputStream(tempFile);

            // 缓冲读取并写入文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = objectContent.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();

            // 2. 转换格式为webp（复用CosManager的图片处理能力）
            String webpKey = "webp/" + message.getPictureId() + ".webp";
            cosManager.putPictureObject(webpKey, tempFile); // COS会自动处理格式转换

            // 3. 更新数据库中的图片URL
            Picture picture = new Picture();
            picture.setId(message.getPictureId());
            picture.setUrl(cosManager.cosClientConfig.getHost() + "/" + webpKey); // 替换为webp地址
            picture.setPicFormat("webp");
            pictureApplicationService.updateById(picture);

            log.info("格式转换完成，pictureId: {}", message.getPictureId());
            channel.basicAck(deliveryTag, false); // 确认消息
        } catch (Exception e) {
            log.error("格式转换失败，pictureId: {}", message.getPictureId(), e);
            channel.basicNack(deliveryTag, false, true); // 失败重试
        } finally {
            // 确保流被关闭
            if (objectContent != null) {
                try {
                    objectContent.close();
                } catch (IOException e) {
                    log.error("关闭输入流失败", e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流失败", e);
                }
            }
        }
    }
}
